// pages/integral/detail/detail.ts
import { getStoreIntegralDetail, confirmIntegralOrder } from '../../../api/points_mall.js';
import { PAGES, goToPage } from '../../../config/pages.js';

Page({
  data: {
    productId: '',
    productInfo: {},
    selectedSku: null,
    quantity: 1,
    userIntegral: 0,
    canBuy: false,
    loading: true,
    showSkuSelector: false,
    skuList: []
  },

  onLoad(options: any) {
    this.setData({ productId: options.id });
    this.getProductDetail();
    this.loadUserIntegral();
  },

  onShow() {
    this.loadUserIntegral();
  },

  // 获取商品详情
  async getProductDetail() {
    try {
      this.setData({ loading: true });
      const res = await getStoreIntegralDetail(this.data.productId);
      this.setData({
        productInfo: res.data,
        userIntegral: res.data.user_integral || 0,
        canBuy: res.data.can_buy || false,
        skuList: res.data.attrs || [],
        selectedSku: res.data.attrs && res.data.attrs.length > 0 ? res.data.attrs[0] : null,
        loading: false
      });
    } catch (error) {
      console.error('获取商品详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none',
      });
      this.setData({ loading: false });
    }
  },

  // 加载用户积分
  loadUserIntegral() {
    const userIntegral = wx.getStorageSync('totalPoints') || 0;
    this.setData({ userIntegral });
  },

  // 显示规格选择器
  showSkuSelector() {
    this.setData({ showSkuSelector: true });
  },

  // 隐藏规格选择器
  hideSkuSelector() {
    this.setData({ showSkuSelector: false });
  },

  // 选择规格
  selectSku(e: any) {
    const { sku } = e.currentTarget.dataset;
    this.setData({ 
      selectedSku: sku,
      showSkuSelector: false
    });
  },

  // 数量变化
  onQuantityChange(e: any) {
    const value = parseInt(e.detail.value) || 1;
    this.setData({ quantity: Math.max(1, value) });
  },

  // 减少数量
  decreaseQuantity() {
    if (this.data.quantity > 1) {
      this.setData({ quantity: this.data.quantity - 1 });
    }
  },

  // 增加数量
  increaseQuantity() {
    this.setData({ quantity: this.data.quantity + 1 });
  },

  // 立即兑换
  async onExchange() {
    if (!this.data.selectedSku) {
      wx.showToast({
        title: '请选择规格',
        icon: 'none',
      });
      return;
    }

    if (!this.data.canBuy) {
      wx.showToast({
        title: '积分不足',
        icon: 'none',
      });
      return;
    }

    try {
      wx.showLoading({ title: '处理中...' });
      const res = await confirmIntegralOrder({
        unique: this.data.selectedSku.unique,
        num: this.data.quantity
      });
      
      // 跳转到订单确认页
      goToPage(PAGES.INTEGRAL_ORDER_CONFIRM, { 
        data: encodeURIComponent(JSON.stringify(res.data)) 
      });
    } catch (error) {
      console.error('确认订单失败:', error);
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none',
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 预览图片
  previewImage(e: any) {
    const { current } = e.currentTarget.dataset;
    const images = this.data.productInfo.images || [];
    wx.previewImage({
      current: current,
      urls: images
    });
  }
});
